package 接口.接口使用实例2;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 姚东名
 * Date: 2024-06-19
 * Time: 16:27
 */

class Student implements Comparable <Student> {
    public String name;
    public int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    //用年龄来比较：
    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }
}
public class Test {
    public static void main4(String[] args) {
        Student[] students = new Student[] {
                new Student("张三", 10),
                new Student("李四", 20),
                new Student("王五", 17),
        };

        System.out.println("排序前：" + Arrays.toString(students));
        //用年龄来比较：
        AgeComparator ageComparator = new AgeComparator();
        Arrays.sort(students, ageComparator);
        System.out.println("排序后：" + Arrays.toString(students));
    }
    public static void main3(String[] args) {
        Student[] students = new Student[] {
                new Student("张三", 10),
                new Student("王五", 17),
                new Student("李四", 20)
        };

        System.out.println("排序前：" + Arrays.toString(students));
        //用姓名来比较：
        NameComparator nameComparator = new NameComparator();
        Arrays.sort(students, nameComparator);
        System.out.println("排序后：" + Arrays.toString(students));
    }
    //手动模拟实现一个Arrays.sort：
    public static void sort(Comparable[] comparables) {
        for (int i = 0; i < comparables.length - 1; i++) {
            for (int j = 0; j < comparables.length - 1 - i; j++) {
                if(comparables[j].compareTo(comparables[j + 1]) > 0) {
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j + 1];
                    comparables[j + 1] = tmp;
                }
            }
        }
    }
    public static void main(String[] args) {
        Student[] students = new Student[] {
                new Student("张三", 10),
                new Student("李四", 20),
                new Student("王五", 17)
        };

        System.out.println("排序前：" + Arrays.toString(students));
        //Arrays.sort(students);
        sort(students);
        System.out.println("排序后：" + Arrays.toString(students));
    }
    public static void main1(String[] args) {
        Student student1 = new Student("张三", 10);
        Student student2 = new Student("李四", 20);

        //用年龄来比较：
        System.out.println(student1 == student2);//false
        System.out.println(student1.compareTo(student2));//-10
    }
}
